import type { CommonState, PageReq, PageRes } from '../common/commonApi'
import { useApi } from '@/composables/useApi'

export const SysDictValueTypes = [
  { label: '无值', value: 'NONE', tagType: 'info' },
  { label: '字符串', value: 'STRING', tagColor: 'green' },
  { label: '自定义', value: 'CUSTOM', tagColor: 'primary' },

] as const
export type SysDictValueType = typeof SysDictValueTypes[number]['value']

/**
 * 系统字典
 */
export interface SysDict {
  /**
   * ID
   */
  id?: number
  /**
   * 字典名称
   */
  dictName?: string
  /**
   * 字典编码
   */
  dictCode?: string
  /**
   * 字典值
   */
  dictValue?: string
  /**
   * 值类型
   */
  valueType?: SysDictValueType
  /**
   * 状态
   */
  state?: CommonState
  /**
   * 上级ID
   */
  parentId?: number
  /**
   * 根ID
   */
  rootId?: number
  /**
   * 优先级
   */
  priority?: number
  /**
   * 当前层级
   */
  level?: number
  /**
   * 最大层级
   */
  maxLevel?: number
  /**
   * 是否叶子节点
   */
  isLeaf?: boolean
  /**
   * 下级资源
   */
  children?: Array<SysDict>

  /**
   * 更新时间
   */
  updateTime?: string

  /**
   * 自定义值
   */
  customData?: Record<string, any>

  /**
   * 自定义字段
   */
  customFields?: SysDictCustomField[]
}

export const SysDictCustomFieldTypes = [
  { label: '字符串', value: 'STRING' },
  { label: '数字', value: 'NUMBER' },
  { label: '布尔', value: 'BOOLEAN' },
] as const
export type SysDictCustomFieldType = typeof SysDictCustomFieldTypes[number]['value']

export interface SysDictCustomField {
  name?: string
  title?: string
  type?: SysDictCustomFieldType
  nullable?: boolean
}

/**
 * 系统文件查询参数
 */
export interface SysDictQuery extends PageReq {
  /**
   * ID
   */
  id?: number
  /**
   * 字典名称
   */
  dictName?: string
  /**
   * 字典编码
   */
  dictCode?: string

  /**
   * 值类型
   */
  valueType?: SysDictValueType

  /**
   * 状态
   */
  state?: CommonState
}

const basePath = '/system/settings/dict'
export const sysDictApi = {
  queryPage: useApi<SysDictQuery, PageRes<SysDict>>(`${basePath}/page`).get,
  findDetail: async (id: number) => useApi<any, SysDict>(`${basePath}/${id}`).get(),
  create: useApi<SysDict, SysDict>(`${basePath}`).post,
  modify: useApi<SysDict, SysDict>(`${basePath}`).patch,
  remove: async (id: number) => useApi<null, SysDict>(`${basePath}/${id}`).remove(),
  queryTree: (rootId: number, level?: number) => useApi<any, SysDict[]>(`${basePath}/${rootId}/tree`).get({ level }),
  queryTreeByRootCode: (rootCode: string) => useApi<any, SysDict[]>(`${basePath}/tree/byRootCode`).get({ rootCode }),
  queryChildren: (parentId: number) => useApi<any, SysDict[]>(`${basePath}/${parentId}/children`).get(),
}
